package com.example.peibei.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.service.presenter.ChcekTextPresenter;
import com.example.peibei.service.presenter.SendPublishPresenter;
import com.example.peibei.service.presenter.SendSquarePresenter;
import com.example.peibei.service.presenter.UploadImagePresenter;
import com.example.peibei.ui.weight.GlideEngine;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.wildma.pictureselector.FileUtils;
import com.yxp.permission.util.lib.PermissionUtil;
import com.yxp.permission.util.lib.callback.PermissionResultCallBack;

import java.util.List;

import butterknife.BindView;

public class SendSquareActivity extends WDActivity {
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.ll_pic)
    LinearLayout ll_pic;
    @BindView(R.id.iv_img_one)
    ImageView iv_img_one;
    @BindView(R.id.iv_img_two)
    ImageView iv_img_two;
    @BindView(R.id.iv_img_three)
    ImageView iv_img_three;
    @BindView(R.id.tv_send_publish)
    TextView tv_send_publish;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.et_dynamic)
    EditText et_dynamic;

    String picturePathOne = "";
    String picturePathTwo = "";
    String picturePathThree = "";
    private UploadImagePresenter uploadImagePresenter;
    private SendSquarePresenter sendPublishPresenter;
    private SPUtils spUtils;
    private String token;
    private ChcekTextPresenter chcekTextPresenter;
    private String content;
    private String id;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_send_dynamic;
    }

    @Override
    protected void initView() {
        tv_title.setText("发布圈子");
        spUtils = new SPUtils(SendSquareActivity.this, SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        id = bundle.getString("id");
        uploadImagePresenter = new UploadImagePresenter(new UploadCall());
        sendPublishPresenter = new SendSquarePresenter(new SendPublishCall());
        chcekTextPresenter = new ChcekTextPresenter(new CheckTextCall());
        iv_back.setOnClickListener(v -> finish());
//        ll_pic.setOnClickListener(v -> showChooseImageDialog());
        ll_pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (picturePathThree.equals("")) {
                    showChooseImageDialog();
                } else {
                    UIUtils.showToastSafe("最多选择三张图片哦");
                }
            }
        });
        tv_send_publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                content = et_dynamic.getText().toString().trim();
                if (content.equals("")) {
                    UIUtils.showToastSafe("内容不能为空");
                    return;
                }
                chcekTextPresenter.reqeust("Bearer " + token, content);
            }
        });
    }

    private void showChooseImageDialog() {
//        PictureSelector
//                .create(SendDynamicActivity.this, PictureSelector.SELECT_REQUEST_CODE)
//                .selectPicture(true);
        getPermission();
    }

    private static String[] PERMISSIONS = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
    };

    private void getPermission() {
        PermissionUtil.getInstance().request(this, PERMISSIONS,
                new PermissionResultCallBack() {
                    @Override
                    public void onPermissionGranted() {
                        showAlbum();
                    }

                    @Override
                    public void onPermissionGranted(String... strings) {
                        // 当所有权限的申请被用户同意之后,该方法会被调用
                        //get_NovelUrl(id);
                    }

                    @Override
                    public void onPermissionDenied(String... permissions) {

                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");

                        // 当权限申请中的某一个或多个权限,被用户曾经否定了,并确认了不再提醒时,也就是权限的申请窗口不能再弹出时,该方法将会被调用
                        getPermission();
                    }

                    @Override
                    public void onRationalShow(String... permissions) {
                        UIUtils.showToastSafe("部分权限被禁止需要手动开启");
                        // 当权限申请中的某一个或多个权限,被用户否定了,但没有确认不再提醒时,也就是权限窗口申请时,但被否定了之后,该方法将会被调用.
                        getPermission();
                    }

                });
    }

    private void showAlbum() {
        PictureSelector.create(SendSquareActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(1)
                .minSelectNum(1)
                .compress(true)
                .selectionMode(PictureConfig.SINGLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /*结果回调*/
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            if (data != null) {
                List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                uploadImage(localMedia.get(0).getCompressPath());
            }
        }
//        if (requestCode == PictureSelector.SELECT_REQUEST_CODE) {
//            if (data != null) {
//                PictureBean pictureBean = data.getParcelableExtra(PictureSelector.PICTURE_RESULT);
//                if (pictureBean.isCut()) {
//                    uploadImage(pictureBean.getPath());
//                } else {
//                    iv_img_one.setImageURI(pictureBean.getUri());
//
//                }
//            }
//        }
    }

    private void uploadImage(String imagePath) {
        if (picturePathOne.equals("")) {
            iv_img_one.setImageBitmap(BitmapFactory.decodeFile(imagePath));
        } else {
            if (picturePathTwo.equals("")) {
                iv_img_two.setImageBitmap(BitmapFactory.decodeFile(imagePath));
            } else {
                iv_img_three.setImageBitmap(BitmapFactory.decodeFile(imagePath));
            }
        }
        uploadImagePresenter.reqeust(imagePath, "Bearer " + token);
    }

    @Override
    protected void destoryData() {
        FileUtils.deleteAllCacheImage(this);
    }

    class UploadCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            Log.i("answer", "图片上传成功：" + data);
            if (picturePathOne.equals("")) {
                picturePathOne = data;
            } else {
                if (picturePathTwo.equals("")) {
                    picturePathTwo = data;
                } else {
                    picturePathThree = data;
                }
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
//            UIUtils.showToastSafe(e.getDisplayMessage());
        }
    }

    class CheckTextCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            String filePath = picturePathOne;
            if (!picturePathTwo.equals("")) {
                filePath = picturePathOne + "," + picturePathTwo;
            }
            if (!picturePathThree.equals("")) {
                filePath = picturePathOne + "," + picturePathTwo + "," + picturePathThree;
            }
            sendPublishPresenter.reqeust("Bearer " + token, et_dynamic.getText().toString(), id, filePath);
        }

        @Override
        public void fail(ApiException e, Object... args) {
            UIUtils.showToastSafe("您的输入含有不合法的内容或图片，请遵守用户协议相关内容");
        }
    }

    class SendPublishCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            UIUtils.showToastSafe("发布成功");
            finish();
            Log.i("answer", "发布圈子成功：" + data);
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }
}
